<template>
    <div class="common-layout">
        <div id="clientEdit">
            <el-dialog v-model="editVisible" title="编辑工单信息" width="1000">
                <el-form ref="createOrderFormRef" :model="formData" label-width="100px">
                    <div id="client" v-if="!checkEngineer">
                        <el-form-item label="产品名称">
                            <el-input v-model="formData.productName"></el-input>
                        </el-form-item>
                        <el-form-item label="客户名称">
                            <el-input v-model="formData.clientName"></el-input>
                        </el-form-item>
                        <el-form-item label="客户电话">
                            <el-input v-model="formData.clientPhone"></el-input>
                        </el-form-item>
                        <el-form-item label="客户地址">
                            <el-input v-model="formData.clientAddress"></el-input>
                        </el-form-item>
                        <el-form-item label="故障描述">
                            <el-input v-model="formData.clientDesc"></el-input>
                        </el-form-item>
                    </div>
                    <div id="engineer" v-else>
                        <el-form-item label="工程师描述">
                            <el-input v-model="formData.engineerDesc"></el-input>
                        </el-form-item>
                        <el-form-item label="工单费用">
                            <el-input v-model="formData.price"></el-input>
                        </el-form-item>
                    </div>
                    <el-form-item>
                        <el-button type="primary" @click="editFormData(formData)">保存</el-button>
                        <!-- <el-button type="primary" @click="cancel" -->
                    </el-form-item>
                </el-form>
            </el-dialog>
        </div>
        <div id="workOrderDetail">
            <el-descriptions class="margin-top" title="工单信息" :column="3" border>
                <template #extra>
                    <!-- <el-button type="primary" v-show="checkEngineer" @click="acceptOrder">接单</el-button> -->
                    <el-button type="primary" @click="editVisible = true">编辑</el-button>

                    <el-button type="success" @click="handleConfirm(formData)"
                        v-show="!checkEngineer && formData.status == 1">确认工单</el-button>

                    <el-button type="success" @click="handlePay(formData)"
                        v-show="!checkEngineer && formData.status == 5">支付</el-button>

                    <el-button type="primary" v-show="checkEngineer" @click="requestMaterial">申请物料</el-button>

                    <el-button type="success" @click="handleRecheckDone(formData)"
                        v-show="checkEngineer && formData.status == 4">复检完成</el-button>

                    <el-button type="danger" v-show="checkEngineer && formData.status != 8"
                        @click="cancelOrder()">取消工单</el-button>
                </template>
                <el-descriptions-item>
                    <template #label>
                        <div class="cell-item">
                            <el-icon>
                                <user />
                            </el-icon>
                            id
                        </div>
                    </template>
                    {{ formData.id }}
                </el-descriptions-item>
                <el-descriptions-item>
                    <template #label>
                        <div class="cell-item">
                            <el-icon>
                                <iphone />
                            </el-icon>
                            客户姓名
                        </div>
                    </template>
                    {{ formData.clientName }}
                </el-descriptions-item>
                <el-descriptions-item>
                    <template #label>
                        <div class="cell-item">
                            <el-icon>
                                <location />
                            </el-icon>
                            客户电话
                        </div>
                    </template>
                    {{ formData.clientPhone }}
                </el-descriptions-item>
                <el-descriptions-item>
                    <template #label>
                        <div class="cell-item">
                            <el-icon>
                                <tickets />
                            </el-icon>
                            客户地址
                        </div>
                    </template>
                    {{ formData.clientAddress }}
                </el-descriptions-item>
                <el-descriptions-item>
                    <template #label>
                        <div class="cell-item">
                            <el-icon>
                                <office-building />
                            </el-icon>
                            客户描述
                        </div>
                    </template>
                    {{ formData.clientDesc }}
                </el-descriptions-item>
                <el-descriptions-item>
                    <template #label>
                        <div class="cell-item">
                            <el-icon>
                                <office-building />
                            </el-icon>
                            产品名称
                        </div>
                    </template>
                    {{ formData.productName }}
                </el-descriptions-item>
                <el-descriptions-item>
                    <template #label>
                        <div class="cell-item">
                            <el-icon>
                                <office-building />
                            </el-icon>
                            工程师描述
                        </div>
                    </template>
                    {{ formData.engineerDesc }}
                </el-descriptions-item>
                <el-descriptions-item>
                    <template #label>
                        <div class="cell-item">
                            <el-icon>
                                <office-building />
                            </el-icon>
                            工单费用
                        </div>
                    </template>
                    {{ formData.price }}
                </el-descriptions-item>
            </el-descriptions>

            <el-divider />

            <div class="processBox">
                <div class="title">
                    工单进度
                    <el-tag type="danger" v-show="formData.status == 8">已取消</el-tag>
                </div>

                <div class="timelineProcessBox">
                    <el-timeline class="timeline">
                        <el-timeline-item class="lineitem"
                            :class="activity.done && formData.status != 8 ? 'active' : 'inactive'"
                            v-for="(activity, index) in activities" :key="index" :timestamp="activity.time">
                            <span style="display: flex; flex-direction: column">
                                <span style="margin: 10px 0; font-size: 16px">
                                    {{ activity.content }}
                                </span>
                                <span style="color: #8c8c8c; font-size: 14px">
                                    {{ activity.people }}
                                </span>
                            </span>
                        </el-timeline-item>
                    </el-timeline>
                </div>
            </div>


            <div class="image">
                <el-divider />
                <div class="title">设备问题照片</div>
                <div v-for="image in formData.imageName" :key="image" class="block">
                    <el-image style="width: 100px; height: 100px" :src="`${imageUrl}/${image}`">
                        <template #error>
                            <div class="image-slot">
                                <el-icon><icon-picture /></el-icon>
                            </div>
                        </template>
                    </el-image>
                </div>
                <el-upload :action="uploadImageUrl" :data="uploadData" multiple :on-success="handleUploadSuccess"
                    :before-upload="beforeImageUpload" v-show="checkEngineer">
                    <el-button type="primary">
                        <el-icon>
                            <UploadFilled />
                        </el-icon>
                        上传
                    </el-button>
                </el-upload>
            </div>


            <div class="video">
                <el-divider />
                <div class="title">复检视频</div>
                <div class="block">
                    <video :src="videoUrl" controls width="50%" :autoplay="false" v-show="uploadVideoButtonShow" />
                    <el-upload class="upload-video" :action="uploadVideoUrl" :data="uploadData"
                        :on-success="handleUploadSuccess" :before-upload="beforeVideoUpload">
                        <el-button type="primary" v-show="!uploadVideoButtonShow && checkEngineer">
                            <el-icon>
                                <UploadFilled />
                            </el-icon>
                            上传
                        </el-button>
                        <template #tip>
                        </template>
                    </el-upload>
                </div>
            </div>

        </div>
    </div>
</template>

<script setup>
import { useRoute, useRouter } from "vue-router";
import { useOrdersStore } from "../../store/order"
import { useUserStore } from "../../store/user";
import EngineerApi from "../../api/engineer"
import OrderApi from "../../api/order"
import { onMounted, ref } from "vue";
import { Picture as IconPicture } from '@element-plus/icons-vue'
import { reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";


const editVisible = ref(false);
const uploadVideoButtonShow = ref(true);
const route = useRoute();
const router = useRouter();
const orderStore = useOrdersStore();
const userStore = useUserStore();
let formData = orderStore.getter.getOrderDetail(route.params.id);

onMounted(async () => {
    const res = await OrderApi.getOrderList(searchForm);
    orderStore.actions.setOrderList(res.data.data.workOrderList);
    if (formData.videoName === null || formData.videoName === "") {
        uploadVideoButtonShow.value = false;
    }
})

const activities = [
    {
        content: '客户创建工单',
        done: formData.status >= 0,
    },
    {
        content: '工程师接单',
        done: formData.status >= 1,
    },
    {
        content: '客户确认',
        done: formData.status >= 2,
    },
    {
        content: '检测处理',
        done: formData.status >= 3,
    },
    {
        content: '复检',
        done: formData.status >= 4,
    },
    {
        content: '待支付',
        done: formData.status >= 5,
    },
    {
        content: '完结',
        done: formData.status >= 6,
    },
]

if (formData.imageName) {
    formData.imageName = formData.imageName.split(",");
}
// 检查用户是否为工程师
const checkEngineer = userStore.state.user.role === "engineer";

// 工程师接单请求
const acceptOrder = () => {
    EngineerApi.acceptOrder(formData.id)
}
// 上传文件附带的参数
const uploadData = ref({
    bizDesc: "ep", //  设备问题(equipment problem)
    id: formData.id // 工单id
})

// 申请物料
const requestMaterial = () => {
    router.push({
        path: "/material",
    })
}

// 上传视频成功后的操作
// const afterUploadVideo = (response) => {
//     formData.videoName = response.data;
//     console.log(videoUrl)
// }

const beforeImageUpload = (file) => {
    // 检查文件格式、大小
    var FileExt = file.name.replace(/.+\./, "");
    const isLt2M = file.size / 1024 / 1024 <= 2;
    var extension = ['jpeg', 'jpg', 'png'].indexOf(FileExt.toLowerCase()) >= 0;
    if (!extension) {
        ElMessage.error('上传图片需要是 JPG 或 PNG 格式!');
        return false;
    }
    if (!isLt2M) {
        ElMessage.error('上传图片大小不能超过 2MB!');
        return false;
    }
}
const beforeVideoUpload = (file) => {
    // 检查文件格式、大小
    var FileExt = file.name.replace(/.+\./, "");
    const isLt10M = file.size / 1024 / 1024 <= 10;
    var extension = ['mp4'].indexOf(FileExt.toLowerCase()) >= 0;
    if (!extension) {
        ElMessage.error('上传视频需要是 MP4 格式!');
        return false;
    }
    if (!isLt10M) {
        ElMessage.error('上传视频大小不能超过 10MB!');
        this.$message.error();
        return false;
    }
}

const searchForm = reactive({
    id: userStore.state.user.id,
    flag: userStore.state.user.role,
})
const handleUploadSuccess = async () => {
    const res = await OrderApi.getOrderList(searchForm);
    orderStore.actions.setOrderList(res.data.data.workOrderList);
    location.reload();
}

// 上传图片成功后的操作
const afterUploadImage = (response) => {
    console.log(response);
}
// 取消工单
const cancelOrder = () => {
    console.log(userStore.state.user.role)
    ElMessageBox.confirm(
        '确定要取消该工单吗?',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(async () => {
        const res = await OrderApi.cancelWorkOrder({ id: formData.id });
        if (res.data.success) {
            ElMessage.success("取消工单成功")
            formData.status = 8
        } else {
            ElMessage.error(res.data.data)
        }
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: '取消删除',
        })
    })
}

const imageUrl = "https://yangcloud.cn:9000/images"

const videoUrl = "https://yangcloud.cn:9000/videos/" + formData.videoName

const uploadImageUrl = "https://yangcloud.cn:8888/api/upload/image"
const uploadVideoUrl = "https://yangcloud.cn:8888/api/upload/video"

const checkVideo = () => {
    return formData.videoName === null ? false : true;
}

const editFormData = async (data) => {
    const res = await OrderApi.updateWorkOrder(data);
    formData = res.data.data;
    orderStore.actions.setOrder(formData);
    location.reload();
}

const handleRecheckDone = async (data) => {
    const res = await OrderApi.recheckDoneWorkOrder(data.id);
    formData = res.data.data;
    orderStore.actions.setOrder(formData);
    location.reload();
}

const handlePay = async (data) => {
    const res = await OrderApi.payWorkOrder(data.id);
    formData = res.data.data;
    orderStore.actions.setOrder(formData);
    location.reload();
}

const handleConfirm = async (data) => {
    const res = await OrderApi.confirmWorkOrder(data);
    formData = res.data.data;
    orderStore.actions.setOrder(formData);
    location.reload();
}

</script>

<style lang="scss" scoped>
.image-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background: var(--el-fill-color-light);
    color: var(--el-text-color-secondary);
    font-size: 30px;
}

.image-slot .el-icon {
    font-size: 30px;
}

.image .block {
    padding: 30px 0;
    text-align: center;
    border-right: solid 1px var(--el-border-color);
    display: inline-block;
    width: 20%;
    box-sizing: border-box;
    vertical-align: top;
}

.image .cell-item {
    font-size: 16px;
    font-weight: 700;
    color: #303133;
}

.title {
    font-size: 16px;
    font-weight: 600;
}

.processBox {
    background-color: #fff;
    height: 210px;


    .timelineProcessBox {
        .timeline {
            display: flex;
            width: 95%;
            margin: 40px auto;

            .lineitem {
                transform: translateX(50%);
                width: 25%;
            }
        }
    }
}

.block {
    margin: 40px auto;
    padding: auto;
}

:deep(.el-timeline-item__tail) {
    border-left: none;
    border-top: 2px solid #e4e7ed;
    width: 100%;
    position: absolute;
    top: 6px;
}

:deep(.el-timeline-item__wrapper) {
    padding-left: 0;
    position: absolute;
    top: 20px;
    transform: translateX(-50%);
    text-align: center;
}

:deep(.el-timeline-item__timestamp) {
    font-size: 14px;
}

.active {
    :deep(.el-timeline-item__node) {
        background-color: #0bbd87;
    }

    :deep(.el-timeline-item__tail) {
        border-color: #0bbd87;
    }
}
</style>